package com.servlet;

import com.bean.AdminBean;
import com.util.DBUtil;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Connection conn = DBUtil.getConnectDb();
        ServletContext sc=this.getServletContext();
        sc.setAttribute("username", username);
        HttpSession session=request.getSession();
        session.setAttribute("username", username);
        int flag=0;
        PreparedStatement stm = null;
        ResultSet rs = null;
        AdminBean admin = new AdminBean();
        String sql = "select * from admin where username='" + username + " 'and password='" + password + "'";
        try {
            stm = conn.prepareStatement(sql);
            rs = stm.executeQuery();
            if (rs.next()) {
                admin.setUserNum(rs.getInt(1));
                admin.setUserName(rs.getString(2));
                admin.setName(rs.getString(3));
                admin.setPassword(rs.getString("password"));
                admin.setStatus(rs.getInt("status"));
                admin.setEmail(rs.getString("email"));
                admin.setSex(rs.getString("sex"));
               flag=1;
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtil.CloseDB(rs, stm, conn);
        }
        if (flag == 1) {
            session.setAttribute("id", admin.getUserNum());
            session.setAttribute("name1", admin.getName());
            if (admin.getStatus() == 1) {
                response.sendRedirect("index_admin.jsp");
            } else {
                response.sendRedirect("index_user.jsp");
            }
        } else {
            response.sendRedirect("login.jsp");
        }
    }
}

